<?php

namespace App\Services;

use App\Constants\CodeResponse;
use App\Exceptions\BusinessException;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Support\Facades\Cache;
use Overtrue\EasySms\Exceptions\NoGatewayAvailableException;

class UserService extends BaseService {

    /**
     * 根据用户名获取用户信息
     * @param  string  $username
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     */
    public function getByUsername(string $username)
    {
        return User::query()->where('username','=',$username)->first();
    }


    /**
     * 发送短信验证码
     * @param  string  $mobile
     * @param  string  $code
     * @throws BusinessException
     */
    public function sendCaptchaMessage(string $mobile,string $code)
    {
        if (!app()->environment('production')) {
            return;
        }
        $sms = app('easysms');
        try {
            $sms->send($mobile, [
                'template' => 'SMS_186614303',
                'data' => [
                    'code' => $code
                ],
            ]);
        } catch (NoGatewayAvailableException $exception) {
            $message = $exception->getException('aliyun')->getMessage();
            throw new BusinessException(CodeResponse::AUTH_CAPTCHA_FAILED,$message ?: '短信发送异常');
        }
    }

    /**
     * 验证短信验证码
     * @param  string  $mobile
     * @param  string  $code
     * @param  string  $key
     * @throws BusinessException
     */
    public function checkCaptcha(string $mobile,string $code,string $key)
    {
        $isPass = $code == Cache::get($key.$mobile);
        if ($isPass) {
            Cache::forget('register_captcha_'.$mobile);
        } else {
            throw new BusinessException(CodeResponse::AUTH_CAPTCHA_UNMATCH);
        }
    }
    /**
     * 验证手机号发送验证码次数是否达到限制
     * @param $mobile
     * @return bool
     * @throws BusinessException
     */
    public function checkMobileCaptchaCount($mobile): bool
    {
        $countKey = 'register_captcha_count_'.$mobile;
        if (Cache::has($countKey)) {
            $count = Cache::increment($countKey);
            if ($count > 10) {
                throw new BusinessException(CodeResponse::AUTH_CAPTCHA_FREQUENCY,'验证码当天发送不能超过10次');
            }
        } else {
            Cache::put($countKey,1,Carbon::tomorrow()->diffInSeconds(now()));
        }
        return true;
    }

    /**
     * @param  string  $mobile
     * @param  string  $key
     * @return string
     */
    public function setCaptcha(string $mobile,string $key): string
    {
        $code = strval(mt_rand(100000, 999999));
        // 非生产环境固定短信验证码
        if (!app()->environment('production')) {
            $code = '111111';
        }
        Cache::put($key.$mobile,$code,600);
        return $code;
    }
}
